<template>
	<view class="video-detail-wrap">
		<view class="video-header" :style="{ height: getSystemInfo.navBarHeight + 'px' }">
			<view class="back" @click="backTop">
				<u-icon size="40" name="arrow-left" color="#fff"></u-icon>
			</view>
		</view>
<!-- 		<view class="mute" @click="handleMute">
			<u-icon name="volume-off" color="#fff" size="50" v-if="isMute"></u-icon>
			<u-icon name="volume" color="#fff" size="50" v-else></u-icon>
		</view> -->
		<u-icon name="photo"></u-icon>
		<view class="video-play">
			<swiper class="swiper" :indicator-dots="false" vertical @change="handleVideo" :current="currentIndex"
				@touchstart="touchStart" @touchend="touchEnd" :muted="isMute">
				<swiper-item v-for="(item,index) in videoList" :key="item.id">
					<view class="video-box">
						<video :id="'myVideo'+ item.id" :src="item.video" :controls="true" @click="pausePlay(item.id)"
							object-fit="contain" :show-center-play-btn="false" :show-play-btn="false"
							:show-fullscreen-btn="false" autoplay v-if="currentIndex==index"
							@ended="onended(item.id)"></video>
						<view class="pause" v-if="pause" @click.stop="startPlay">
							<view class="pause-btn">
								<image
									src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/rescue/pause.png">
								</image>
							</view>
						</view>
						<view class="video-content">
							<view>{{ item.content }}</view>
						</view>
					</view>
					<view class="video-bottom">
						<view class="video-oprate">
							<view class="atv">
								<image :src="item.terminalImg?item.terminalImg:'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/index/mratv.png'"></image>
								<view class="name">{{item.name }}</view>
							</view>
							<view class="btn">
								<view class="share" @click="handleShare(item)">
									<u-icon name="share-square" color="#fff" size="60"></u-icon>
									{{item.forward }}
								</view>
								<view class="thumb-up">
									<u-icon name="thumb-up" :color="item.isLikes?'#CF1A1B':'#fff'" size="60"
										@click="setLike(item)"></u-icon>
									{{item.likes }}
								</view>
                <view class="comment" @click="handleComment(item)">
									<u-icon name="chat" color="#fff" size="60"></u-icon>
                  <text>{{item.commentNum }}</text>
								</view> 
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 分享 -->
		<u-popup :show="popupShow" :round="20" mode="bottom" @close="popupClose" :closeOnClickOverlay="true">
			<view class="popup-content">
				<view class="pc-title">分享到</view>
				<view class="pc-list">
					<view class="pc-item" v-for="item in popupList" :key="item.type"
						@click.stop="handlePopupClick(item.type)">
						<view class="pci-box" v-if="item.type === 'weChat'">
							<button open-type="share">
								<image class="pci-image" :src="item.url" mode=""></image>
								<view class="pci-label">
									{{ item.label }}
								</view>
							</button>
						</view>
						<view class="pci-box" v-else>
							<image class="pci-image" :src="item.url" mode=""></image>
							<view class="pci-label">
								{{ item.label }}
							</view>
						</view>
					</view>
				</view>
				<view class="pc-btn" @click.stop="popupShow = false">取消</view>
			</view>
		</u-popup>
		<!-- 举报、屏蔽 -->
		<u-action-sheet class="action-sheet" :round="20" :show="operShow" :actions="operList" :closeOnClickAction="true"
			:closeOnClickOverlay="true" cancelText="取消" cancelTextClass="cancelTextClass" @select="operSelectClick"
			@close="operSelectCancel"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>

	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex'
	export default {
		name: 'video-detail',
		computed: {
			...mapGetters('global', ['getSystemInfo']),
			...mapGetters('user', ['getUserInfo']),
		},
		data() {
			return {
				source: '', // 判断来源是 卡友家园（大咖说）,还是 视频列表
				videoList: [],
				pageNum: 1,
				pageSize: 20,
				pause: false,
				videoContext: null,
				videoInfo: null,
				popupShow: false,
				popupList: [{
						url: 'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/circle/ic_weChat.png',
						label: '微信好友',
						type: 'weChat'
					},
					{
						url: 'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/circle/ic_copy.png',
						label: '复制链接',
						type: 'copy'
					},
					{
						url: 'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/circle/ic_report.png',
						label: '举报',
						type: 'report'
					},
					{
						url: 'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/circle/ic_shield.png',
						label: '屏蔽',
						type: 'shield'
					}
				],
				operShow: false, // 举报、屏蔽选择列表
				operType: null, // 区分举报 还是 屏蔽
				operList: [], // 选项列表
				reportList: [ // 举报列表
					{
						name: '淫秽色情',
						type: 1
					},
					{
						name: '操作违规',
						type: 2
					},
					{
						name: '言语辱骂',
						type: 3
					},
					{
						name: '营销广告',
						type: 4
					},
				],
				shieldList: [ // 屏蔽列表
					{
						name: '屏蔽@作者昵称',
						type: 'user'
					},
					{
						name: '屏蔽此条卡友圈',
						type: 'one'
					},
				],
				currId: '',
				videoId: '',
				pageStartY: 0,
				pageEndY: 0,
				timer: null,
				currentIndex: 0,
				pageNum: 1,
				fristInto: true,
				filterIds: [],
				isMute: true
			}
		},
		mounted() {
			this.videoContext = uni.createVideoContext("myVideo" + this.videoId, this)
			this.videoContext.play()
		},
		methods: {
      
      // 校验视频是否存在
      async existShow(id){
      	return new Promise((resolve, reject) => {
      		this.$request({
      			method: 'GET',
      			url: '/terminal-serve-center/app/cars/existShow',
      			data: {
      				id
      			}
      		}).then(res => {
      			resolve(res.datas.existFlag)
      		}).catch(res => {
      			reject(res.datas.existFlag)
      		})
      	})
      },
      
			// 初始化页面
			async initData() {
				//获取服务协议
				if (this.source && this.fristInto) {
					try {
						const res = await this.$request({
							url: '/terminal-serve-center/app/cars/getLoveItemVideo',
							data: {
								userId: this.getUserInfo.id,
							}
						})
						res.datas.forEach(i => {
							// shieldUser-用户  shieldThis-此条
							i.shieldUser = 0  // 0-未屏蔽, 1-已屏蔽
							i.shieldThis = 0
						})
						this.videoList = res.datas
						if (this.fristInto) {
							this.videoId = this.currId
							this.videoInfo = this.videoList[this.currentIndex]
							this.fristInto = false
						}
						res.datas.forEach((item) => {
							this.filterIds.push(item.id)
						})
						const res2 = await this.$request({
							url: '/terminal-serve-center/app/cars/getVideoList',
							data: {
								pageNum: 1,
								pageSize: 10,
								userId: this.getUserInfo.id,
								filterShowIds: this.filterIds
							}
						})
						res2.datas.data.forEach(i => {
							// shieldUser-用户  shieldThis-此条
							i.shieldUser = 0  // 0-未屏蔽, 1-已屏蔽
							i.shieldThis = 0
						})
						this.videoList = this.videoList.concat(res2.datas.data)

					} catch (e) {}
				} else {
					try {
						const res = await this.$request({
							url: '/terminal-serve-center/app/cars/getVideoList',
							data: {
								pageNum: this.pageNum,
								pageSize: 10,
								userId: this.getUserInfo.id
							}
						})
						if (this.fristInto) {
							this.videoId = this.currId
							res.datas.data.forEach((item, index) => {
								if (item.id == this.videoId) {
									this.videoInfo = item
									this.currentIndex = index

								}
							})

							this.fristInto = false
						}
						res.datas.data.forEach(i => {
							// shieldUser-用户  shieldThis-此条
							i.shieldUser = 0  // 0-未屏蔽, 1-已屏蔽
							i.shieldThis = 0
						})
						this.videoList = this.videoList.concat(res.datas.data)

					} catch (e) {

					}
				}
			},
			operSelectCancel() {
				this.operShow = false
			},
			operSelectClick(data) {
				this.operShow = false
				if (this.operType === 'report') { // 举报
					this.handleReport(data.type)
				} else { // 屏蔽
					// 0-未屏蔽, 1-已屏蔽
					if (data.type === 'user') { // 屏蔽用户
						this.handleShield(this.videoInfo.shieldUser === 0 ? 1 : 3, data.type)
					} else { // 屏蔽此条
						this.handleShield(this.videoInfo.shieldThis === 0 ? 2 : 4, data.type)
					}
				}
			},
			// 举报函数
			async handleReport(type) {
				await this.$request({
					methods: 'POST',
					url: '/terminal-serve-center/app/cars/reportShow',
					data: {
						id: this.videoInfo.id,
						type
					}
				}).then(res => {
					uni.showToast({
						title: '举报成功',
						icon: 'none'
					})
				}).catch(res => {
					uni.showToast({
						title: '您已经举报过了',
						icon: 'none'
					})
				})
			},
			// 屏蔽函数
			async handleShield(type, dataType) {
				// 	屏蔽类型(1-屏蔽用户,2-屏蔽卡友圈,3-取消屏蔽用户,4-取消屏蔽卡友圈)
				await this.$request({
					method: 'POST',
					url: '/terminal-serve-center/app/cars/blockShow',
					data: {
						userId: this.getUserInfo.id,
						id: this.videoInfo.id,
						showUserId: this.videoInfo.userId,
						type
					}
				}).then(res => {
					if (dataType === 'user') { // 屏蔽用户
						this.videoInfo.shieldUser = this.videoInfo.shieldUser == 0 ? 1 : 0
					} else { // 屏蔽此条
						this.videoInfo.shieldThis = this.videoInfo.shieldThis == 0 ? 1 : 0
					}
					uni.showToast({
						title: (type === 1 || type === 2) ? '屏蔽成功' : '取消屏蔽成功',
						icon: 'none'
					})
				}).catch(res => {
					uni.showToast({
						title: res.respMsg,
						icon: 'none'
					})
				})
			},
      
      async judgeVieoExit(val) {
        const checkStatus = await this.existShow(val.id)
        if(!checkStatus){
        	uni.showToast({
        		title: '操作失败，该视频已被删除',
        		icon: 'none',
        	})
        	setTimeout(() => {
            uni.reLaunch({
              url: `/videoPack/videoList/index`
            })
        	}, 500)
        	return false
        } 
      },
      
			// 分享 
			handleShare(item) {
				this.popupShow = true
			},
      
      // 评论
     async handleComment(item) {
        const checkStatus = await this.existShow(item.id)
        if(!checkStatus){
        	uni.showToast({
        		title: '操作失败，该视频已被删除',
        		icon: 'none',
        	})
        	setTimeout(() => {
           uni.reLaunch({
             url: `/videoPack/videoList/index`
           })
        	}, 1000)
        	return false
        } else {
          const { id, shieldUser, shieldThis } = this.videoInfo
          uni.navigateTo({
            url: `/circlePack/detail/index?id=${id}&shieldUser=${shieldUser}&shieldThis=${shieldThis}&source=video`
          })
        } 
      },
			popupClose() {
				this.popupShow = false
			},
			async handlePopupClick(type) {
        // 屏蔽操作不做校验，其它操作需要校验卡友圈的状态才能继续
        if(type !== 'shield'){
         const checkStatus = await this.existShow(this.videoInfo.id)
         if(!checkStatus){
            uni.showToast({
              title: '操作失败，该视频已被删除',
              icon: 'none',
            })
            setTimeout(() => {
              this.popupClose()
              uni.reLaunch({
                url: `/videoPack/videoList/index`
              })
            }, 1000)
            return false
          }
        }
        
				if (type === 'weChat') { // 微信-分享

				} else if (type === 'copy') { // 复制
					// const pages = getCurrentPages() // 获取栈实例
					// const baseUrl = this.baseUrl //项目的域名
					// const currentRoute  = pages[pages.length-1].route; // 获取当前页面路由
					// const currentPage = baseUrl + pages[pages.length-1]['$page']['fullPath'] //当前页面路径(带参数)

					// uni.setClipboardData({
					// 	data: currentPage, // 复制的内容 
					// 	success: res => {
					// 		console.log('success', res);
					// 		uni.showToast({
					// 			title: '复制成功',
					// 			duration: 1000
					// 		})
					// 	}
					// });
					let params = {
						// path：要跳转到的小程序的目标页面纯路径（不要拼接参数）
						// 注意：如果该链接要打开的版本是正式版，则这个path一定要已经发布到了正式版，不然无法访问到该页面则链接无法生成成功
						// path: '/circlePack/detail/index',
						// path: '/pages/circle/index',
						// path: '/videoPack/videoList/index',
						query: "", // 短链的入参
						env_version: "trial", // 默认值"release"。要打开的小程序版本。正式版为 "release"，体验版为"trial"，开发版为"develop"，仅在微信外打开时生效。
						expire_type: 1,
						expire_interval: 30,
					}
					const url = await this.getAppLink(params)
				} else if (type === 'report') { // 举报
					this.operType = 'report'
					this.operList = this.reportList
					this.operShow = true
				} else { // 屏蔽
					this.operType = 'shield'
					let tempList = []
					// 0-未屏蔽, 1-已屏蔽
					this.shieldList[0].name = this.videoInfo.shieldUser === 0 ? `屏蔽@${this.videoInfo.name}` :
						`取消屏蔽@${this.videoInfo.name}`
					this.shieldList[1].name = this.videoInfo.shieldThis === 0 ? `屏蔽此条视频` : '取消屏蔽此条视频'
					this.operList = this.shieldList
					this.operShow = true
				}
				this.popupShow = false
			},
			async getAppLink(params) {
				// AppID(小程序ID)
				const appid = this.$appid
				// AppSecret(小程序密钥)
				const secret = this.$secret
				// 先发起请求获取凭证
				await uni.request({
					url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
					method: 'GET',
					success: async res => {
						// console.log('获取凭证', res);
						// 再发起请求获取url
						await uni.request({
							url: `https://api.weixin.qq.com/wxa/generate_urllink?access_token=${res.data.access_token}`,
							method: 'POST',
							data: {
								...params
							},
							success: result => {
								// console.log(result);
								console.log('生成网址：', result.data);

								uni.setClipboardData({
									data: result.data.url_link, // 复制的内容 
									success: function() {
										uni.showToast({
											title: '复制成功',
											duration: 1000
										})
									}
								});
								// return result.data.url_link
							}
						})
					}
				})
			},
			//开始播放
			startPlay() {
				this.videoContext.play()
				this.pause = false
			},
			//暂停播放
			pausePlay(id) {
				this.videoContext = uni.createVideoContext("myVideo" + id, this)
				this.videoContext.pause()
				this.pause = true
			},
			//静音
			handleMute() {
				this.isMute = !this.isMute

			},
			onended(id) {
				console.log(2)
				this.videoContext = uni.createVideoContext("myVideo" + id, this)
				this.videoContext.seek(0)
				this.videoContext.pause()
				this.pause = true
			},
			//视频切换
			handleVideo(event) {
				this.videoContext.pause()
				this.videoContext.stop();
				this.timer = null
				this.currentIndex = event.detail.current
				this.videoContext = uni.createVideoContext("myVideo" + this.videoList[this.currentIndex].id, this)
				this.videoInfo = this.videoList[this.currentIndex]
				this.videoContext.seek(0)
				this.pause = false
				this.videoContext.play()
				if (this.currentIndex == this.videoList.length - 1) {
					this.pageNum++
					this.initData()
				}
			},
			//判断是下滑上划
			touchStart(res) {
				this.pageStartY = res.changedTouches[0].pageY;
			},
			touchEnd(res) {
				this.pageEndY = res.changedTouches[0].pageY;
			},
			//返回上一页
			backTop() {
				uni.navigateBack()
			},
			async setLike(item) {
        this.judgeVieoExit(item)
				try {
					const res = await this.$request({
						url: '/terminal-serve-center/app/cars/storeShowLikes',
						data: {
							isLikes: this.videoInfo.isLikes ? 0 : 1,
							userId: this.getUserInfo.id,
							id: this.videoInfo.id
						}
					})
					if (this.videoInfo.isLikes) {
						this.$refs.uToast.show({
							message: '点赞已取消！',
						})
						this.videoInfo.isLikes = 0
						this.videoList[this.currentIndex].likes = this.videoInfo.likes - 1
					} else {
						this.$refs.uToast.show({
							message: '谢谢点赞！',
						})
						this.videoInfo.isLikes = 1
						this.videoList[this.currentIndex].likes = this.videoInfo.likes + 1
					}


				} catch (e) {

				}
			},
		},
		onShow() {

		},
		onLoad(option) {
			this.currId = option.id
			this.source = option.source || '' // 判断来源是 卡友家园（大咖说）,还是 视频列表
			this.fristInto = true
			if (this.source) {
				this.pageNum = 1
				this.currentIndex = option.currentIndex
			} else {
				this.pageNum = parseInt(option.pageNum)
			}
			this.initData()

		},
		// 分享给朋友
		onShareAppMessage(res) {
			this.$request({
				method: 'POST',
				url: '/terminal-serve-center/app/cars/storeShowForward',
				data: {
					id: this.videoInfo.id
				}
			})
			this.videoInfo.forward = this.videoInfo.forward + 1
			return {
				title: this.videoInfo.content,
				path: `/videoPack/videoList/index`,
				imageUrl: this.videoInfo.coverVideo
			}
			if (res.from === 'button') {

			}

		},
	}
</script>

<style scoped lang="scss">
	.video-detail-wrap {
		height: 100%;
		width: 100%;
		overflow: hidden;
		position: fixed;
		top: 0;
		left: 0;

		// 分享
		.popup-content {
			width: 100%;
			display: flex;
			flex-direction: column;
			background-color: #F7F8FA;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			overflow: hidden;

			.pc-title {
				width: 100%;
				text-align: center;
				padding: 40rpx 0;
				font-size: 14px;
				color: #323233;
				background-color: #ffffff;
			}

			.pc-list {
				display: flex;
				justify-content: space-between;
				box-sizing: border-box;
				padding: 0 48rpx;
				background-color: #ffffff;

				.pc-item {
					padding-bottom: 32rpx;

					.pci-box {
						display: flex;
						flex-direction: column;
						align-items: center;

						button {
							padding: 0;
							border: none;
							background-color: transparent;
							box-shadow: none;
							font-size: 12px;
							color: #646566;
							line-height: 16px;

							&::after {
								border: none;
								height: auto;
							}
						}
					}

					.pci-image {
						width: 96rpx;
						height: 96rpx;
						vertical-align: bottom;
					}

					.pci-label {
						margin-top: 16rpx;
						font-size: 12px;
						color: #646566;
					}
				}
			}

			.pc-btn {
				margin-top: 16rpx;
				width: 100%;
				text-align: center;
				padding: 26rpx 0;
				font-size: 16px;
				color: #646566;
				background-color: #ffffff;
			}

		}

		.mute {
			position: absolute;
			right: 30rpx;
			top: 180rpx;
			padding: 10rpx;
			z-index: 11;
		}

		.video-header {
			position: absolute;
			top: 0;
			background: linear-gradient(180deg, #000000 0%, rgba(0, 0, 0, 0) 100%);
			opacity: 1;
			width: 100%;
			z-index: 10;

			.back {
				padding-top: 80rpx;
				padding-left: 20rpx;
				display: flex;
				width: 100rpx;
				align-items: center;
			}
		}

		.video-play {
			height: 100%;
			width: 100%;
			position: relative;
			background: #000000;

			.swiper {
				height: 100%;

				.video-box {
					height: calc(100% - 172rpx);
					position: relative;

					video {
						height: 100%;
						width: 100%;
					}

					.pause {
						position: absolute;
						height: 100%;
						width: 100%;
						left: 0;
						top: 0;
						z-index: 20;

						.pause-btn {
							width: 100%;
							height: 100%;
							justify-content: center;
							display: flex;
							align-items: center;
							align-content: center;
						}

						image {
							width: 84rpx;
							height: 96rpx;
						}
					}

					.video-content {
						position: absolute;
						width: 80%;
						bottom: 82rpx;
						opacity: 1;
						color: #fff;
						margin: 0 20rpx;

						view {
							word-wrap: break-all;
							overflow: hidden;
							line-break: anywhere;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							line-clamp: 2;
							-webkit-box-orient: vertical;
							width: 100%;
						}
					}
				}

			}
		}

		.video-bottom {
			height: 104rpx;
			padding-bottom: 68rpx;
			background: #000000;

			.video-oprate {
				display: flex;
				justify-content: space-between;
				color: #fff;
				padding: 20rpx 0;
			}

			.atv {
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 16px;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #FFFFFF;

				image {
					width: 68rpx;
					height: 68rpx;
					border-radius: 50%;
					margin: 0 10rpx;
					background: #fff;
				}
			}

			.btn {
				display: flex;
				justify-content: center;
				align-items: center;

				.share,
				.thumb-up,
        .comment {
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.thumb-up {
					margin: 0 20rpx;
				}
        .comment {
          margin-left: 0;
          margin-right: 20rpx;
        }
			}

		}
	}
</style>